package com.boilermaker.lotterysystem.service.statusconvert.operator;

import com.boilermaker.lotterysystem.dao.dataobject.ActivityDO;
import com.boilermaker.lotterysystem.dao.mapper.ActivityMapper;
import com.boilermaker.lotterysystem.dao.mapper.ActivityPrizeMapper;
import com.boilermaker.lotterysystem.service.dto.ConvertStatusDTO;
import com.boilermaker.lotterysystem.service.enums.ActivityPrizeStatusEnum;
import com.boilermaker.lotterysystem.service.enums.ActivityStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ActivityStatusOperator extends AbstractStatusOperator {

    @Autowired
    private ActivityMapper activityMapper;

    @Autowired
    private ActivityPrizeMapper activityPrizeMapper;

    @Override
    public Integer sequence() {
        return 2;
    }

    @Override
    public Boolean convertPolicy(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        ActivityStatusEnum targetStatus = dto.getTargetActivityStatus();

        if (activityId == null || targetStatus == null) {
            return false;
        }

        // 若关联的奖品尚没被全部抽完（存在状态为 AVAILABLE 的奖品），则不能转换
        if (activityPrizeMapper.countByStatus(activityId,
                ActivityPrizeStatusEnum.AVAILABLE.name()) != 0) {
            return false;
        }

        ActivityDO activityDO = activityMapper.selectById(activityId);
        // 若原状态与目标状态一致，则不能转换
        return activityDO != null
                && !activityDO.getStatus().equalsIgnoreCase(targetStatus.name());
    }

    @Override
    public Boolean convert(ConvertStatusDTO dto) {

        Long activityId = dto.getActivityId();
        ActivityStatusEnum targetStatus = dto.getTargetActivityStatus();

        try {
            activityMapper.updateStatus(activityId, targetStatus.name());
            return true;
        } catch (Exception e) {
            log.error("状态转换异常", e);
            return false;
        }
    }
}
